home *** CD-ROM | disk | FTP | other *** search
- Path: Rezonet.net!news
- From: ray@ultimate-tech.com (Ray Dunn)
- Newsgroups: comp.lang.c
- Subject: Re: swap high and low 16 bits?
- Date: 18 Jan 1996 04:23:33 GMT
- Organization: Ultimate Technographics Inc.
- Message-ID: <4dki05$104c@ns.RezoNet.NET>
- References: <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: 204.19.230.7
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.7
-
- In referenced article, Bill Simpson says...
- >
- >I wanted to obtain a "random" starting number each time a program
- >is run. The obvious choice is time(NULL). The problem with it is
- >that if the program runs and terminates fairly quickly, the number
- >returned by time(NULL) is quite similar each run, differing only by
- >the lowest bits.
-
- If you use the number you get from time as the seed of the random
- number generator i.e. srand((unsigned int)time(NULL)); then use rand()
- to get a random number in the range 0 to RAND_MAX (which is usually the
- maximum integer) This should be exactly what you want. The rand
- functions are defined in stdlib.h;
-
- >One solution would be to swap the high 16 bits and the low 16 bits of
- >the 32 bit unsigned long int. Sorry this is dirty, not ANSI.
-
- This would give you a number that was numerically very different each
- time, but the low 16-bits would be the same every run. Probably not
- what you want, but you can do it easily in arithmetic:
-
- number = (number >> 16) | (number << 16);
-
- If you don't currently understand bitwise operations, then try:
-
- number = number / 65536 + (number % 65536) * 65536;
-
- [ % is the modulus operator - it produces the remainder, and is
- required to avoid the * 65536 giving integer overflow, which may
- cause a trap on you machine]
-
- number must be unsigned for this to have the effect you want.
- --
- Ray Dunn (opinions are my own) | Phone: (514) 938 9050
- Montreal | Phax : (514) 938 5225
- ray@ultimate-tech.com | Home : (514) 630 3749
-
-